package com.lcz.ssm.controller;

import com.lcz.ssm.model.IsLogin;
import com.lcz.ssm.utils.AjaxResponse;
import com.lcz.ssm.utils.DateUtils;
import com.lcz.ssm.utils.ResponseEnum;
import net.rubyeye.xmemcached.MemcachedClient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Value
 * <p/>
 * Copyright (c) 2012 Value ValueSoft Inc., All rights reserved.
 * <p/>
 * This software is the confidential and proprietary information of
 * ValueSoft Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with ValueSoft.com.
 * <p/>
 * Revision History
 * Date      		Programmer       Notes
 * 13-10-15   	     laborc		     Initial
 * *********************************************************************
 */
public abstract class BaseController {
    private static final Log logger = LogFactory.getLog(BaseController.class);

    public static final String PAGE_ATTR = "pageAttr";
    /**
     * 保存用户到SESSION
     */
    public static final String PROXY = "proxy";
    public static final String USER_SESSION = "USER_SESSION";
    public static final String STUDENT = "student";
    public static final String USER = "user";
    public static final String TRAINING_CLASS = "trainingClass";
    public static final String TRAINING_CLASS_LIST = "trainingClassList";
    public static final String LOGIN_PAGE = "loginPre";
    public static final String ADD = "add";
    public static final String SUCCESS = "success";
    public static final String ERROR = "error"; //change to success as to show error message in the same page.
    public static final String LIST_SUCCESS = "list_success";
    public static final String READ_SUCCESS = "read_success";
    public static final String ADD_SUCCESS = "add_success";
    public static final String DELETE_SUCCESS = "delete_success";
    public static final String CONTINUE_ADD = "continue_add";
    public static final int BUYSUCCESS = 1;     // 购买课程成功
    public static final int BUYFAILD = -1;      // 购买课程失败
    public static final int WHETHERBUY = 0;     // 是否购买课程
    public static final int ALREADYBUY = 2;     // 已经购买该课程
    //modify by cxj begin
    public static final String FAIL="fail";
    public static final String QUEREN="确认";
    public static final String XINGCE="行测";
    public static final String SHENLUN="申论";
    public static final String YIPIGAI="已批改";
    public static final String WEIPIGAI="未批改";
    public static final String WEISHENHE="未审核";
    public static final String FUKUANCHENGGONG="付款成功";
    public static final String YANZHENGSHIBAI="验证失败";
    public static final String YANZHENGCHENGGONG="验证成功";
    public static final String CHONGZHICHONGGONG="充值成功！";
    public static final String FUKUANXINXI="付款信息";
    public static final String YIFUKUAN="已付款";
    public static final String DATATRANSFAIL="数据传输失败！";
    public static final String LOGINFIRST="用户还没登陆，请先登陆";
    public static final String CHONGZHIWRONG="充值卡号或密码错误";
    public static final String UPDATEPWDSUCCESS="修改密码成功！";
    public static final String ORDERNUMBER="订单号";
    public static final String TDRETURN="回复TD退订";
    public static final String MAILBANK="邮箱不能为空";
    public static final String MAILWRONG="邮件格式不正确";
    public static final String PHONEBANK="手机号码不能为空";
    public static final String PHONEWRONG="手机号码格式不正确";
    public static final String CONTACTADMIN="系统出错，请联系系统管理员";
    public static final String BUYFIRST="目前您还没购买，无法使用，请先购买";
    public static final String CHONGZHIONLYONCE="该学习卡已经被充值，不能再次充值！";
    public static final String WELCOMEREGISTER="欢迎您注册微博课堂，您注册验证码：";
    public static final String TRACTUS="您已成功购买微博课堂课程！具体开课时间请关注新浪微博“微博课堂校园”或者微信公共账号“微博课堂”，如有问题请联系4000480048";
    //modify by cxj end

    protected void setParams(ModelAndView view){
    }

    /**
     * 创建视图
     *
     * @param ftl
     * @return
     */
    protected Boolean buildViewWithOutJson(HttpServletRequest request, String ftl) {
        String path = request.getRequestURI();
        if (path.indexOf(".")!=-1){
            if(path.split("\\.").length>1){
                path = path.split("\\.")[1];
                if(path!=null && ("json").equals(path)){
                    return false;
                }else{
                    return  true;
                }
            }else{
                return true;
            }
        }else{
            return true;
        }
    }


    /**
     * 创建视图
     *
     * @param ftl
     * @return
     */
    protected ModelAndView buildView(HttpServletRequest request, String ftl) {
        ModelAndView view = new ModelAndView("/ftl/" + ftl);

        view.addObject("spmout", "");
        view.addObject("dev", "1");
        view.addObject("timestamp", DateUtils.formatDateTime(new Date()));
        view.addObject("resServer", "");

        this.setParams(view);
        return view;
    }


    protected ModelAndView loginOutView(HttpServletRequest request) {
        AjaxResponse response = buildAjaxResponse(request);
        IsLogin isLogin = new IsLogin();
        isLogin.setIsLogin(false);
        response.addModel(isLogin);
        response.setStat(ResponseEnum.ERROR);
        response.setSilent(true);
        return response.getMav();
    }


    /**
     * 初始化ajax响应
     * @param request
     * @return
     */
    protected AjaxResponse buildAjaxResponse(HttpServletRequest request) {
        AjaxResponse response = new AjaxResponse(request, memcachedClient, getJsonPath());
        return response;
    }

    /**
     * 构建异常编号
     *
     * @param request
     * @return
     */
    protected String buildErrorCode(HttpServletRequest request) {
        String path = request.getRequestURI().substring(request.getContextPath().length());
        path = path.substring(1);
        path = path.replace("/", ".");
        String method = request.getParameter("_method");
        if (StringUtils.isBlank(method)) {
            method = request.getMethod();
        }
        return path + ":" + method.toLowerCase();
    }

    protected String decode(String str){
        if (StringUtils.isBlank(str)){
            return null;
        }
        String target = "";
        try {
            target = URLDecoder.decode(str, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e);
        }
        return target;
    }

    protected String getJsonPath() {
        return "";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        //对于需要转换为Date类型的属性，使用DateEditor进行处理

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 利用@InitBinder来注册customer propertyEditor
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     * @param binder
     * @review 2014-01-17 wwb <bin2302@gmail.com>
     * @example
     *      @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
     *      private Date lastLoginDate;
     */
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // true:允许输入空值，false:不能为空值
        CustomDateEditor dateEditor = new CustomDateEditor(dateFormat, true);

        binder.registerCustomEditor(Date.class, dateEditor);

        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (text == null || (text = text.trim()).length() == 0) {
                    return;
                }
                try {
                    //去除html标签
                    String str = text.replaceAll("<[a-zA-Z]+[1-9]?[^><]*>", "")
                            .replaceAll("</[a-zA-Z]+[1-9]?>", "");
                    str = encode(str);
                    setValue(str);
                } catch (Exception e) {
                    throw new IllegalArgumentException(e);
                }
            }
        });

    }

    /**
     * 替换内容中的特殊符号
     * @return
     * @Author
     */
    public static String encode(String s) {
        if (s == null)
            return null;
        s = s.replace("<w:br/>", "");

        StringBuffer sb = new StringBuffer();
        int n = s.length();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            switch (c) {
                case ' ':
                    sb.append("");
                    break;
                case '\r':
                    sb.append("");
                    break;
                case '<':
                    sb.append("");
                    break; // 为防止script攻击，转为全角
                case '>':
                    sb.append("");
                    break;
                case '&':
                    sb.append("");
                    break;
                case '"':
                    sb.append("");
                    break;
                case '\\':
                    sb.append("");
                    break;
                case '\'':
                    sb.append("");
                    break;
                case '\n':
                    sb.append(" ");
                    break;

                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }

    @Autowired
    protected MemcachedClient memcachedClient;

}
